package smy.att.devices;

import smy.att.ADB;
import smy.att.Helper;

import java.io.IOException;
import java.io.InputStream;
import java.lang.Runtime;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class VirtualBox implements ISimulator{
	Runtime rt = Runtime.getRuntime();
	String  vbox_manage_name  = "vboxmanage";
	String  vbox_android_name;

	public String Name() {
		return "192.168.56.101:5555";
	}
	private String VmName() {
		// lazy calculate
		if (vbox_android_name != null)
		{
			return vbox_android_name;
		}
		
		// Get the virtual box name
		try {
			// Get vbox manager output
			Process process = rt.exec(new String[]{vbox_manage_name , "list" , "vms"});
			InputStream process_output_stream = process.getInputStream();
			String output = Helper.ReadInputStream(process_output_stream);
			Pattern pattern = Pattern.compile("\"(andro[^\"]*)\"");
			Matcher matcher = pattern.matcher(output);
			if (matcher.find())
			{
				vbox_android_name = matcher.group(1);
				return vbox_android_name;
			}
			else
			{
				throw new IOException("Cannot Find Android Virtual Machine");
			}
		} catch (IOException e) {
			System.out.println("Cannot Find VboxManage");
			System.out.println(e);
			throw new RuntimeException("Error While Find Vbox");
		}
	}

	@Override
	public void Start() {
		try {
			// Start the process
			rt.exec(new String[]{vbox_manage_name , "startvm", VmName()});
		} catch (IOException e) {
			System.out.println("Error While Start The Virtual Machine");
			System.out.println(e);
			throw new RuntimeException("Error While Start Android Simulator");
		}
	}

	@Override
	public void Stop() {
		try {
			// Start the process
			rt.exec(new String[]{vbox_manage_name, "controlvm" ,VmName(),"poweroff"});
		} catch (IOException e) {
			System.out.println("Error While Stop The Virtual Machine");
			System.out.println(e);
			throw new RuntimeException("Error While Start Android Simulator");
		}
	}

	@Override
	public void Connect(ADB adb) {
		// TODO : Auto Detect the Android Virtual Machine
		try {
			rt.exec(new String[]{"adb" , "connect" , "192.168.56.101"});
		} catch (IOException e) {
			System.out.println("Error While Connect To the Android Debug Bridge");
			System.out.println(e);
			throw new RuntimeException("Error While Connect To the Android Debug Bridge");
		}
	}

	@Override
	public Boolean IsAvailable() {
		try {
			Process proc = rt.exec(new String[]{vbox_manage_name , "list" , "runningvms"});
			String  result = Helper.ReadInputStream(proc.getInputStream());
			if (result.contains(VmName())) {
				return true;
			}
		} catch (IOException e) {
			System.out.println("Error While Detect The Running VM");
			System.out.println(e);
			throw new RuntimeException("Error While Start Android Simulator");
		}
		return false;
	}
	
}
